from datetime import datetime, timedelta
from django.utils import timezone as django_timezone
from rest_framework import serializers, status
from rest_framework.views import APIView
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
from NetShop.models import CustomLogin
import base64
from rest_framework.response import Response
from captcha.views import CaptchaStore, captcha_image
from rest_framework.decorators import api_view
from PetNetadmin.serializers import CustomLoginMessageSerializer
from NetShop.utils.aliyunphone import sms_phone
import random
from django.core.cache import cache
from NetShop.tasks import sms_phone_c


# 图片验证码

class CaptchaAPIView(APIView):
    def get(self, request):
        hashkey = CaptchaStore.generate_key()
        id = CaptchaStore.objects.filter(hashkey=hashkey).first().id
        imgage = captcha_image(request, hashkey)
        # 将图片转换为base64
        image_base = base64.b64encode(imgage.content)
        json_data = {
            "key": id,
            "image_base": "data:image/png;base64," + image_base.decode('utf-8'),
            'code': 2000,
            'msg': '获取成功'
        }
        return Response(data=json_data)


# 前台商城登录
class CustomLoginSerializer(TokenObtainPairSerializer):
    captcha = serializers.CharField(max_length=6)

    class Meta:
        model = CustomLogin
        fields = "__all__"
        read_only_fields = ["id"]

    def validate(self, attrs):
        username = attrs['username']
        password = attrs['password']
        captcha = attrs['captcha'].lower()
        image_code = CaptchaStore.objects.filter(response=captcha).first()
        # 将当前时间转换为带有时区信息的对象
        current_time = django_timezone.now()
        five_minute_ago = current_time - timedelta(hours=0, minutes=5, seconds=0)
        custom = CustomLogin.objects.filter(username=username).first()
        if not custom:
            result = {
                "code": 4000,
                "msg": "账号/密码不正确",
            }
            return result
        status = custom.status
        if status =='2':
            result = {
                'code':4000,
                'msg': '账号已被封禁，请联系管理员！！！'
            }
            return result
        if image_code and five_minute_ago > image_code.expiration:
            image_code and image_code.delete()
            result = {
                "code": 4000,
                "msg": "验证码过期",
            }
            return result
        else:
            if image_code and (image_code.response == captcha or image_code.challenge == captcha):
                image_code and image_code.delete()
            else:
                image_code and image_code.delete()
                result = {
                    "code": 4000,
                    "msg": "图片验证码错误",
                }
                return result
        refresh = self.get_token(custom)
        data = {"userId": custom.id,
                "user_name": custom.name,
                'username': custom.username,
                "token": str(refresh.access_token),
                'exp': refresh.access_token.payload['exp'],
                "refresh": str(refresh),
                "code": 2000,
                'msg': '登陆成功'
                }
        return data


class LoginView(TokenObtainPairView):
    """
    登录接口
    """
    serializer_class = CustomLoginSerializer
    permission_classes = []


@api_view(['POST'])
def get_mobile_code(request):
    print(request.data)
    mobile = request.data['mobile']
    code = random.randrange(1000, 9999)
    cache_key = 'sms_%s' % (mobile)
    cache.set(cache_key, code, 60)
    # 添入celery
    sms_phone_c.delay(mobile,code)
    print('经过这里')
    # {'PhoneNumbers': '19959797519',
    # 'SignName': '阿里云短信测试',
    # 'TemplateCode': 'SMS_154950909',s
    # 'TemplateParam': '{"code":"9605"}'}
    # print(code)
    # 将验证码写进redis缓存

    result = {
        'code': 2000,
        'msg': '发送验证码成功,请在1分钟内写入'
    }
    return Response(data=result, status=status.HTTP_200_OK)


# 注册
@api_view(['POST'])
def CustomRegister(request):
    get_message = request.data
    # 测试号码 19959797519
    mobile = get_message['mobile']
    mobile_captcha = get_message['mobile_captcha']
    print(mobile,mobile_captcha)
    cache_key = 'sms_%s' % (mobile)
    code = cache.get(cache_key)
    print(code)
    if code==None:
        result = {
            'msg':'验证码不存在，请重新发送'
        }
        return Response(result,status=status.HTTP_404_NOT_FOUND)
        if get_message['mobile_captcha'] != code:
            result = {
                'msg': '验证码验证不成功'
            }
            return Response(result,status=status.HTTP_404_NOT_FOUND)
    serializer = CustomLoginMessageSerializer(data=get_message, partial=True)
    if serializer.is_valid(raise_exception=True):
        serializer.save()
        result = {
            'code': 2000,
            'msg': '注册成功'
        }
        return Response(status=status.HTTP_200_OK, data=result)
    return Response({"msg": '出了点问题噢!!!'}, status=status.HTTP_400_BAD_REQUEST, )
